package network.websocket;


import eventbus.PageEventBus;
import eventbus.PageEvents;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * ws发送器
 * 借助于netty的Channel完成消息发送到客户端,但只能发送文本类消息
 *
 * @author wyl
 */
public class WSServerSender {

    public static void sendAll(Object o) {
        ChannelManager.getChannelGroup()
                .writeAndFlush(buildTextFrame(o));
        PageEventBus.publish(PageEvents.ADD_TRAFFIC_EVENT);
    }

    public static void send(String channelLongId, Object o) {
        ChannelManager.getChannel(channelLongId)
                .writeAndFlush(buildTextFrame(o));
        PageEventBus.publish(PageEvents.ADD_TRAFFIC_EVENT);
    }

    public static void send(Channel channel, Object o) {
        channel.writeAndFlush(buildTextFrame(o));
        PageEventBus.publish(PageEvents.ADD_TRAFFIC_EVENT);
    }


    private static TextWebSocketFrame buildTextFrame(Object o) {
        return new TextWebSocketFrame(WSDtoConverter.buildWSDtoJson(o));
    }

}
